package com.tjec.project.companyLibrary.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import com.tjec.common.constant.Constants;
import com.tjec.common.exception.UtilException;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.interceptor.annotation.RepeatSubmit;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsExpertPerson;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsMdExpertType;
import com.tjec.project.projectLeaderWorkbeanch.service.IBmsExpertPersonService;
import com.tjec.project.projectLeaderWorkbeanch.service.IBmsMdExpertTypeService;
import com.tjec.project.system.domain.BmsAttachment;
import com.tjec.project.system.domain.SysRole;
import com.tjec.project.system.service.ISysRoleService;
import com.tjec.project.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tjec.framework.aspectj.lang.annotation.Log;
import com.tjec.framework.aspectj.lang.enums.BusinessType;
import com.tjec.project.companyLibrary.domain.BmsExpertCompany;
import com.tjec.project.companyLibrary.service.IBmsExpertCompanyService;
import com.tjec.framework.web.controller.BaseController;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.framework.web.page.TableDataInfo;

/**
 * 企业专家Controller
 * 
 * @author tjec
 * @date 2020-04-22
 */
@Api(value = "企业专家库接口" , tags = {"企业专家库接口"})
@RestController
@RequestMapping("/companyLibrary/companyExpert")
public class BmsExpertCompanyController extends BaseController
{
    @Autowired
    private IBmsExpertCompanyService bmsExpertCompanyService;

    @Autowired
    private IBmsExpertPersonService bmsExpertPersonService;

    @Autowired
    private IBmsMdExpertTypeService bmsMdExpertTypeService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Value("${sftp.http}")
    private String http;
    @Value("${sftp.ip}")
    private String ip;

    /**
     * 查询企业专家列表
     */
    @ApiOperation("查询企业专家列表")
//    @PreAuthorize("@ss.hasPermi('companyLibrary:companyExpert:list')")
    @GetMapping("/list")
    public TableDataInfo list(BmsExpertCompany bmsExpertCompany)
    {
        startPage();
        List<BmsExpertCompany> list = bmsExpertCompanyService.selectBmsExpertCompanyList(bmsExpertCompany);
        for (BmsExpertCompany expertCompany : list) {
            parsExpertCompany(expertCompany);
        }
        return getDataTable(list);
    }

    /**
     * 是否包含公司专家库管理员角色
     */
    @ApiOperation("是否包含公司专家库管理员角色")
//    @PreAuthorize("@ss.hasPermi('companyLibrary:companyExpert:list')")
    @GetMapping("/isCompanyExpertAdmin")
    public AjaxResult isCompanyExpertAdmin()
    {
        Boolean isCompanyExpertAdmin = false;
        String currentUserId = SecurityUtils.getLoginUser().getUser().getUserId();
        if(SecurityUtils.isAdmin(currentUserId)){
            isCompanyExpertAdmin = true;
        }else{
            List<String> list = sysRoleService.selectRoleListByUserId(currentUserId);
            SysRole sysRole = sysRoleService.selectRoleByRoleKey(Constants.ROLE_ENTERPRISE_EXPERT_LIBRARY_ADMIN_KEY);
            if(list.contains(sysRole.getRoleId())){
                isCompanyExpertAdmin = true;
            }
        }
        return AjaxResult.success(isCompanyExpertAdmin);
    }

    /**
     *
     * @param expertCompany
     * @return
     */
    public void parsExpertCompany(BmsExpertCompany expertCompany ){
        if(StringUtils.isNotBlank(expertCompany.getProfessionCategory())){
            List<BmsMdExpertType> professionCategoryExpertType = bmsMdExpertTypeService.selectBmsMdExpertTypeByGuids(expertCompany.getProfessionCategory().split(";"));
            String professionCategoryNames = "";
            for (BmsMdExpertType bmsMdExpertType : professionCategoryExpertType) {
                professionCategoryNames += bmsMdExpertType.getCname()+";";
            }
            expertCompany.setProfessionCategoryName(professionCategoryNames);
        }
        if(StringUtils.isNotBlank(expertCompany.getProfessionCategory())){
            expertCompany.setProfessionCategorys( expertCompany.getProfessionCategory().split(";"));
        }
        if(StringUtils.isNotBlank(expertCompany.getBusinessMerit())){
            expertCompany.setBusinessMerits( expertCompany.getBusinessMerit().split(";"));
        }
        if(StringUtils.isNotBlank(expertCompany.getIndustryMerit())){
            expertCompany.setIndustryMerits( expertCompany.getIndustryMerit().split(";"));
        }
        if(!CollectionUtils.isEmpty(expertCompany.getBmsAttachments())){
            ArrayList<String> attIds = new ArrayList<>();
            for (BmsAttachment bmsAttachment : expertCompany.getBmsAttachments()) {
                bmsAttachment.setStoragePath(http + ip +Constants.RESOURCE_PREFIX + bmsAttachment.getStoragePath());
                attIds.add(bmsAttachment.getGuid());
            }
            expertCompany.setAttachmentIds(attIds);
        }
    }

    /**
     * 获取企业专家详细信息
     */
    @ApiOperation("获取企业专家详细信息")
    @ApiImplicitParam(name = "guid", value = "企业专家guid", required = true, dataType = "String", paramType = "path")
//    @PreAuthorize("@ss.hasPermi('companyLibrary:companyExpert:query')")
    @GetMapping(value = "/{guid}")
    public AjaxResult getInfo(@PathVariable("guid") String guid)
    {
        BmsExpertCompany expertCompany = bmsExpertCompanyService.selectBmsExpertCompanyByGuid(guid);
        parsExpertCompany(expertCompany);
        return AjaxResult.success(expertCompany);
    }

    /**
     * 新增企业专家
     */
    @ApiOperation("新增企业专家")
    @ApiImplicitParam(name = "bmsExpertCompany", value = "新增个人专家", dataType = "BmsExpertCompany")
//    @PreAuthorize("@ss.hasPermi('companyLibrary:companyExpert:add')")
    @Log(title = "企业专家", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@RequestBody BmsExpertCompany bmsExpertCompany) throws Exception
    {
        /*if(insertCheck(bmsExpertCompany)){
            throw new UtilException("新增专家'" + bmsExpertCompany.getName() + "'失败，专家身份证号'" + bmsExpertCompany.getIdentityCard() + "'在企业专家库中已存在");
        }*/
        return toAjax(bmsExpertCompanyService.insertBmsExpertCompany(bmsExpertCompany));
    }

    /**
     * 新增企业专家校验省份证号
     * @param bmsExpertCompany
     * @throws Exception
     */
    public boolean insertCheck(BmsExpertCompany bmsExpertCompany){
        //校验是否重复
        BmsExpertCompany bmsExpertCompanyCheck = new BmsExpertCompany();
        bmsExpertCompanyCheck.setIdentityCard(bmsExpertCompany.getIdentityCard());
        List<BmsExpertCompany> list = bmsExpertCompanyService.selectBmsExpertCompanyList(bmsExpertCompanyCheck);
        if(null != list && list.size() > 0){
            return true;
        }else{
            return  false;
        }
    }

    /**
     * 批量新增企业专家
     */
    @ApiOperation("推荐至企业专家库接口")
    @ApiImplicitParam(name = "bmsExpertCompany", value = "新增个人专家", dataType = "Array")
//    @PreAuthorize("@ss.hasPermi('companyLibrary:companyExpert:batchAdd')")
    @Log(title = "企业专家", businessType = BusinessType.INSERT)
    @PostMapping("/batchAdd")
    public AjaxResult batchAdd(@RequestBody List<BmsExpertCompany> bmsExpertCompanys) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success();
        for (BmsExpertCompany bmsExpertCompany : bmsExpertCompanys) {
            if(insertCheck(bmsExpertCompany)){
                throw new UtilException("推荐专家'" + bmsExpertCompany.getName() + "'至企业专家库失败，专家身份证号'" + bmsExpertCompany.getIdentityCard() + "'在企业专家库中已存在");
            }
            //专家Guid
            String bmsExpertPersonGuid = bmsExpertCompany.getGuid();
            if(StringUtils.isBlank(bmsExpertCompany.getExpertSource())){
                BmsExpertPerson bmsExpertPerson = bmsExpertPersonService.selectBmsExpertPersonByGuid(bmsExpertCompany.getGuid());
                bmsExpertCompany.setExpertSource(null!=bmsExpertPerson?bmsExpertPerson.getProjectLeader():"");
            }
            bmsExpertCompany.setGuid(UUID.randomUUID().toString());
            int row = bmsExpertCompanyService.insertBmsExpertCompany(bmsExpertCompany);
            //更新个人专家推荐状态为已推荐
            BmsExpertPerson bmsExpertPerson = new BmsExpertPerson();
            bmsExpertPerson.setGuid(bmsExpertPersonGuid);
            bmsExpertPerson.setRecommendStatus("1");
            bmsExpertPersonService.updateBmsExpertPerson(bmsExpertPerson);
            if(row <= 0){
                ajaxResult = ajaxResult.error();
                break;
            }
        }
        return ajaxResult;
    }

    /**
     * 修改企业专家
     */
    @ApiOperation("修改企业专家")
    @ApiImplicitParam(name = "BmsExpertCompany", value = "修改企业专家", dataType = "BmsExpertCompany")
//    @PreAuthorize("@ss.hasPermi('companyLibrary:companyExpert:edit')")
    @Log(title = "企业专家", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BmsExpertCompany bmsExpertCompany)
    {
        /*if(updateCheck(bmsExpertCompany)){
            throw new UtilException("修改专家'" + bmsExpertCompany.getName() + "'失败，专家身份证号'" + bmsExpertCompany.getIdentityCard() + "'在企业专家库中已存在");
        }*/
        return toAjax(bmsExpertCompanyService.updateBmsExpertCompany(bmsExpertCompany));
    }

    /**
     * 修改企业专家校验省份证号
     * @param bmsExpertCompany
     * @throws Exception
     */
    public boolean updateCheck(BmsExpertCompany bmsExpertCompany){
        //校验是否重复
        BmsExpertCompany bmsExpertCompanyCheck = new BmsExpertCompany();
        bmsExpertCompanyCheck.setIdentityCard(bmsExpertCompany.getIdentityCard());
        List<BmsExpertCompany> list = bmsExpertCompanyService.selectBmsExpertCompanyList(bmsExpertCompanyCheck);
        //过滤当前修改专家ID
        list = list.stream().filter(s -> !s.getGuid().equals(bmsExpertCompany.getGuid())).collect(Collectors.toList());
        if(null != list && list.size() > 0){
            return true;
        }else{
            return false;
        }
    }
}
